#!/bin/bash

# Feng Admin 生产环境停止脚本 (Linux)
# 用于安全地停止和清理生产环境服务

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 清屏
clear

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Feng Admin - 生产环境停止${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 检查项目根目录
if [ ! -d "apps/backend" ] || [ ! -d "apps/frontend" ]; then
    echo -e "${RED}错误: 请在项目根目录下运行此脚本${NC}"
    exit 1
fi

# 函数: 停止前台进程
stop_foreground_processes() {
    echo -e "${CYAN}停止前台进程...${NC}"
    
    # 停止 Python HTTP 服务器
    pkill -f "python.*http.server" 2>/dev/null
    pkill -f "python3.*http.server" 2>/dev/null
    
    # 停止 Flask 应用
    pkill -f "python.*app.py" 2>/dev/null
    pkill -f "python3.*app.py" 2>/dev/null
    
    # 停止 Gunicorn 进程
    pkill -f "gunicorn.*app:app" 2>/dev/null
    
    echo -e "${GREEN}✓ 前台进程已停止${NC}"
}

# 函数: 停止 PM2 服务
stop_pm2_services() {
    echo -e "${CYAN}停止 PM2 服务...${NC}"
    
    if command -v pm2 &> /dev/null; then
        # 停止 Feng Admin 相关进程
        pm2 stop feng-admin-backend 2>/dev/null
        pm2 stop feng-admin-frontend 2>/dev/null
        
        # 删除进程
        pm2 delete feng-admin-backend 2>/dev/null
        pm2 delete feng-admin-frontend 2>/dev/null
        
        echo -e "${GREEN}✓ PM2 服务已停止${NC}"
    else
        echo -e "${YELLOW}⚠️  PM2 未安装，跳过${NC}"
    fi
}

# 函数: 停止 Supervisor 服务
stop_supervisor_services() {
    echo -e "${CYAN}停止 Supervisor 服务...${NC}"
    
    if command -v supervisorctl &> /dev/null; then
        # 停止服务
        sudo supervisorctl stop feng-admin-backend 2>/dev/null
        
        # 删除配置
        if [ -f "/etc/supervisor/conf.d/feng-admin.conf" ]; then
            echo "删除 Supervisor 配置文件..."
            sudo rm -f /etc/supervisor/conf.d/feng-admin.conf
            sudo supervisorctl reread 2>/dev/null
            sudo supervisorctl update 2>/dev/null
        fi
        
        echo -e "${GREEN}✓ Supervisor 服务已停止${NC}"
    else
        echo -e "${YELLOW}⚠️  Supervisor 未安装，跳过${NC}"
    fi
}

# 函数: 停止 Systemd 服务
stop_systemd_services() {
    echo -e "${CYAN}停止 Systemd 服务...${NC}"
    
    if command -v systemctl &> /dev/null; then
        # 停止服务
        sudo systemctl stop feng-admin-backend 2>/dev/null
        
        # 禁用服务
        sudo systemctl disable feng-admin-backend 2>/dev/null
        
        # 删除服务文件
        if [ -f "/etc/systemd/system/feng-admin-backend.service" ]; then
            echo "删除 Systemd 服务文件..."
            sudo rm -f /etc/systemd/system/feng-admin-backend.service
            sudo systemctl daemon-reload 2>/dev/null
        fi
        
        echo -e "${GREEN}✓ Systemd 服务已停止${NC}"
    else
        echo -e "${YELLOW}⚠️  Systemd 不可用，跳过${NC}"
    fi
}

# 函数: 清理端口占用
cleanup_ports() {
    echo -e "${CYAN}清理端口占用...${NC}"
    
    # 读取配置文件中的端口
    if [ -f "apps/backend/.env" ]; then
        # 从配置文件读取端口
        eval $(grep "^BACKEND_PORT=" apps/backend/.env 2>/dev/null)
        eval $(grep "^CORS_ORIGINS=" apps/backend/.env 2>/dev/null)
        
        # 提取前端端口
        if [[ "$CORS_ORIGINS" == *:* ]]; then
            frontend_port=$(echo "$CORS_ORIGINS" | sed 's/.*://')
        else
            frontend_port="5173"  # 默认端口
        fi
        
        backend_port=${BACKEND_PORT:-5001}
        
        echo "清理端口 ${backend_port} (后端) 和 ${frontend_port} (前端)..."
        
        # 清理后端端口
        if command -v lsof &> /dev/null; then
            lsof -ti:${backend_port} | xargs kill -9 2>/dev/null
            lsof -ti:${frontend_port} | xargs kill -9 2>/dev/null
        elif command -v netstat &> /dev/null; then
            # 使用 netstat 查找进程
            netstat -tuln | grep ":${backend_port} " | awk '{print $7}' | cut -d'/' -f1 | xargs kill -9 2>/dev/null
            netstat -tuln | grep ":${frontend_port} " | awk '{print $7}' | cut -d'/' -f1 | xargs kill -9 2>/dev/null
        fi
    else
        echo -e "${YELLOW}⚠️  未找到配置文件，清理默认端口...${NC}"
        # 清理默认端口
        if command -v lsof &> /dev/null; then
            lsof -ti:5001 | xargs kill -9 2>/dev/null
            lsof -ti:5173 | xargs kill -9 2>/dev/null
        fi
    fi
    
    echo -e "${GREEN}✓ 端口已清理${NC}"
}

# 函数: 清理日志文件
cleanup_logs() {
    echo -e "${CYAN}清理日志文件...${NC}"
    
    # 清理项目日志
    rm -f apps/backend/*.log 2>/dev/null
    rm -f apps/frontend/*.log 2>/dev/null
    
    # 清理系统日志目录
    if [ -d "/var/log/feng-admin" ]; then
        echo "清理系统日志目录..."
        sudo rm -rf /var/log/feng-admin
    fi
    
    echo -e "${GREEN}✓ 日志文件已清理${NC}"
}

# 函数: 清理临时文件
cleanup_temp_files() {
    echo -e "${CYAN}清理临时文件...${NC}"
    
    # 清理构建文件
    rm -rf apps/frontend/dist 2>/dev/null
    rm -rf apps/frontend/node_modules/.cache 2>/dev/null
    
    # 清理 Python 缓存
    find . -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null
    find . -name "*.pyc" -delete 2>/dev/null
    
    # 清理 npm 缓存
    if [ -d "apps/frontend/node_modules" ]; then
        cd apps/frontend
        npm cache clean --force 2>/dev/null
        cd ../..
    fi
    
    echo -e "${GREEN}✓ 临时文件已清理${NC}"
}

# 函数: 备份数据库
backup_database() {
    echo -e "${CYAN}备份数据库...${NC}"
    
    if [ -f "apps/backend/instance/feng_admin.db" ]; then
        backup_dir="backups"
        mkdir -p "$backup_dir"
        
        timestamp=$(date +"%Y%m%d_%H%M%S")
        backup_file="$backup_dir/feng_admin_${timestamp}.db"
        
        cp "apps/backend/instance/feng_admin.db" "$backup_file"
        echo -e "${GREEN}✓ 数据库已备份到: $backup_file${NC}"
    else
        echo -e "${YELLOW}⚠️  未找到数据库文件${NC}"
    fi
}

# 主菜单
echo "请选择停止方式:"
echo "  1. 智能停止 (推荐) - 自动检测并停止所有服务"
echo "  2. 停止前台进程"
echo "  3. 停止 PM2 服务"
echo "  4. 停止 Supervisor 服务"
echo "  5. 停止 Systemd 服务"
echo "  6. 完全清理 (停止所有服务 + 清理文件)"
echo "  7. 仅清理端口占用"
echo ""
read -p "请选择 (1-7): " stop_mode

case $stop_mode in
    1)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  智能停止服务${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        stop_foreground_processes
        stop_pm2_services
        stop_supervisor_services
        stop_systemd_services
        cleanup_ports
        
        echo ""
        echo -e "${GREEN}✓ 智能停止完成${NC}"
        ;;
        
    2)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  停止前台进程${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        stop_foreground_processes
        cleanup_ports
        ;;
        
    3)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  停止 PM2 服务${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        stop_pm2_services
        ;;
        
    4)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  停止 Supervisor 服务${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        stop_supervisor_services
        ;;
        
    5)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  停止 Systemd 服务${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        stop_systemd_services
        ;;
        
    6)
        echo ""
        echo -e "${YELLOW}⚠️  完全清理模式${NC}"
        echo ""
        echo "这将执行以下操作:"
        echo "  - 停止所有服务"
        echo "  - 清理端口占用"
        echo "  - 备份数据库"
        echo "  - 清理日志文件"
        echo "  - 清理临时文件"
        echo ""
        read -p "确认继续? (y/N): " confirm_cleanup
        
        if [[ $confirm_cleanup =~ ^[Yy]$ ]]; then
            echo ""
            echo -e "${BLUE}========================================${NC}"
            echo -e "${BLUE}  完全清理${NC}"
            echo -e "${BLUE}========================================${NC}"
            echo ""
            
            backup_database
            stop_foreground_processes
            stop_pm2_services
            stop_supervisor_services
            stop_systemd_services
            cleanup_ports
            cleanup_logs
            cleanup_temp_files
            
            echo ""
            echo -e "${GREEN}✓ 完全清理完成${NC}"
        else
            echo -e "${YELLOW}操作已取消${NC}"
            exit 0
        fi
        ;;
        
    7)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  清理端口占用${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        cleanup_ports
        ;;
        
    *)
        echo -e "${RED}无效的选项${NC}"
        exit 1
        ;;
esac

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  停止完成！${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 显示状态检查
echo -e "${CYAN}状态检查:${NC}"
echo ""

# 检查端口占用
if [ -f "apps/backend/.env" ]; then
    eval $(grep "^BACKEND_PORT=" apps/backend/.env 2>/dev/null)
    eval $(grep "^CORS_ORIGINS=" apps/backend/.env 2>/dev/null)
    
    if [[ "$CORS_ORIGINS" == *:* ]]; then
        frontend_port=$(echo "$CORS_ORIGINS" | sed 's/.*://')
    else
        frontend_port="5173"
    fi
    
    backend_port=${BACKEND_PORT:-5001}
    
    # 检查端口状态
    if command -v lsof &> /dev/null; then
        if lsof -i:${backend_port} &> /dev/null; then
            echo -e "后端端口 ${backend_port}: ${RED}仍被占用${NC}"
        else
            echo -e "后端端口 ${backend_port}: ${GREEN}已释放${NC}"
        fi
        
        if lsof -i:${frontend_port} &> /dev/null; then
            echo -e "前端端口 ${frontend_port}: ${RED}仍被占用${NC}"
        else
            echo -e "前端端口 ${frontend_port}: ${GREEN}已释放${NC}"
        fi
    fi
fi

# 检查进程状态
if pgrep -f "python.*app.py" &> /dev/null; then
    echo -e "Flask 进程: ${RED}仍在运行${NC}"
else
    echo -e "Flask 进程: ${GREEN}已停止${NC}"
fi

if pgrep -f "gunicorn.*app:app" &> /dev/null; then
    echo -e "Gunicorn 进程: ${RED}仍在运行${NC}"
else
    echo -e "Gunicorn 进程: ${GREEN}已停止${NC}"
fi

if command -v pm2 &> /dev/null; then
    if pm2 list | grep -q "feng-admin"; then
        echo -e "PM2 服务: ${RED}仍有相关进程${NC}"
    else
        echo -e "PM2 服务: ${GREEN}已清理${NC}"
    fi
fi

echo ""
echo -e "${YELLOW}提示:${NC}"
echo "  - 如需重新启动，运行: ./start-prod.sh"
echo "  - 如需查看日志，检查: apps/backend/ 目录"
echo "  - 数据库文件位置: apps/backend/instance/feng_admin.db"
echo ""

# 询问是否删除配置文件
echo -e "${YELLOW}是否删除配置文件? (apps/backend/.env, apps/frontend/.env)${NC}"
read -p "删除配置文件? (y/N): " delete_config

if [[ $delete_config =~ ^[Yy]$ ]]; then
    rm -f apps/backend/.env
    rm -f apps/frontend/.env
    echo -e "${GREEN}✓ 配置文件已删除${NC}"
    echo -e "${YELLOW}注意: 下次启动需要重新配置${NC}"
fi

echo ""
echo -e "${GREEN}停止脚本执行完成！${NC}"
echo ""
